package com.tinem.platform.service.robot.im.adaptation.hjxc;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tinem.platform.module.pojo.co.GatewayHeadName;
import com.tinem.platform.module.starter.sdk.MessageCode;
import com.tinem.platform.module.starter.sdk.core.BaseApi;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Component
public class Api extends BaseApi {
    private static final Logger log = LoggerFactory.getLogger(Api.class);
    @Resource
    HjxcAutoProperties hjxcAutoProperties;

    @Value("${INSTANCE_NAME}")
    String device;

    String access_token;
    JSONObject userInfo;

    public String token(){
        return HttpUtil.get(StrUtil.format(
                "{}/oauth/token?client_id={}&client_secret={}&grant_type=client_credentials",
                hjxcAutoProperties.authUrl(),
                hjxcAutoProperties.clientId(),
                hjxcAutoProperties.clientSecret()
        ));
    }
    public JSONObject login(
    ){
        JSONObject params = new JSONObject();
        params.put("account",hjxcAutoProperties.account());
        params.put("password",hjxcAutoProperties.password());
        params.put("platform","browser");
        params.put("pushClientId","");
        params.put("version","1.0.0");
        return post(hjxcAutoProperties.module(),"/login.api",params);
    }
    public JSONObject userInfo(
    ){
        JSONObject params = new JSONObject();
        params.put("platform","browser");
        params.put("version","1.0.0");
        return post(hjxcAutoProperties.module(),"/user/info.api",params);
    }

    public JSONObject sendMessage(
            String toId,
            String chatRoomId,
            String content
    ){
        JSONObject params = new JSONObject();
        params.put("chatRoomId",chatRoomId);
        params.put("content",content);
        params.put("msgType","msg_txt");
        params.put("toId",toId);
        params.put("platform","browser");
        params.put("version","1.0.0");
        return post(hjxcAutoProperties.module(),"/message/sendMsg.api",params);
    }

    public JSONObject post(String module, String api, Object body){
        long startTime = System.currentTimeMillis();
        HttpRequest request = HttpUtil.createPost(StrUtil.format(hjxcAutoProperties.gatewayUrl(), startTime));
        request.header(GatewayHeadName.X_PLATFORM_GATEWAY_REQ_SERVICE,module);
        request.header(GatewayHeadName.X_PLATFORM_GATEWAY_REQ_METHOD,api);
        request.header(GatewayHeadName.X_PLATFORM_GATEWAY_REQ_VERSION,"0.0.1-SNAPSHOT");
        request.header(GatewayHeadName.X_PLATFORM_GATEWAY_REQ_API_REQUEST_ID, UUID.randomUUID().toString());
        request.header(GatewayHeadName.X_PLATFORM_GATEWAY_REQ_CHARSET,"UTF-8");
        request.header(GatewayHeadName.X_PLATFORM_GATEWAY_REQ_LANG,"en-us");
        request.header(GatewayHeadName.X_PLATFORM_GATEWAY_REQ_DEVICE,device);
        request.header(GatewayHeadName.X_PLATFORM_GATEWAY_REQ_JWT,access_token);
        request.header("Authorization",StrUtil.format("Bearer {}",access_token));
        request.body(JSON.toJSONString(body),"application/json");
        log.info("req id:({}); service:({}); method:({});"
                ,request.header(GatewayHeadName.X_PLATFORM_GATEWAY_REQ_API_REQUEST_ID)
                ,request.header(GatewayHeadName.X_PLATFORM_GATEWAY_REQ_SERVICE)
                ,request.header(GatewayHeadName.X_PLATFORM_GATEWAY_REQ_METHOD)
        );
        HttpResponse httpResponse = request.execute();
        long endTime = System.currentTimeMillis();
        log.info("execute time start({}) end({}) continued:({});",startTime,endTime,endTime-startTime);
        log.debug("httpResponse head:{}:{}",GatewayHeadName.X_PLATFORM_GATEWAY_RES_CODE,httpResponse.header(GatewayHeadName.X_PLATFORM_GATEWAY_RES_CODE));
        log.debug("httpResponse head:{}:{}",GatewayHeadName.X_PLATFORM_GATEWAY_RES_MESSAGE,httpResponse.header(GatewayHeadName.X_PLATFORM_GATEWAY_RES_MESSAGE));
        log.debug("httpResponse head:{}:{}",GatewayHeadName.X_PLATFORM_RES_CODE,httpResponse.header(GatewayHeadName.X_PLATFORM_RES_CODE));
        log.debug("httpResponse head:{}:{}",GatewayHeadName.X_PLATFORM_RES_MESSAGE,httpResponse.header(GatewayHeadName.X_PLATFORM_RES_MESSAGE));
        log.debug("httpResponse head:{}:{}",GatewayHeadName.X_PLATFORM_GATEWAY_REQUEST_ID,httpResponse.header(GatewayHeadName.X_PLATFORM_GATEWAY_REQUEST_ID));
        // 请求正常
        if(httpResponse.getStatus() != 200){
            log.error("http status:({});Http body:{}",httpResponse.getStatus(),httpResponse.body());
            throw new HttpException(httpResponse.getStatus()+"");
        }
        // 网关状态码正确
        if(!MessageCode.SUCCESS.name().equalsIgnoreCase(httpResponse.header(GatewayHeadName.X_PLATFORM_GATEWAY_RES_CODE))){
            log.error("gateway code:({}); message:{}"
                    , httpResponse.header(GatewayHeadName.X_PLATFORM_GATEWAY_RES_CODE)
                    , httpResponse.header(GatewayHeadName.X_PLATFORM_GATEWAY_RES_MESSAGE));
            throw new HttpException(httpResponse.getStatus()+"");
        }
        // 业务状态码正常
        if(!MessageCode.SUCCESS.name().equalsIgnoreCase(httpResponse.header(GatewayHeadName.X_PLATFORM_RES_CODE))){
            log.error("gateway code:({}); message:{}"
                    , httpResponse.header(GatewayHeadName.X_PLATFORM_RES_CODE)
                    , Base64.decode(httpResponse.header(GatewayHeadName.X_PLATFORM_RES_MESSAGE)));
            throw new HttpException(httpResponse.getStatus()+"");
        }
        return JSON.parseObject(httpResponse.body());
    }

}
